﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text.RegularExpressions;

namespace CRM.Common
{
   public static class JsonHelper
    {
        /// <summary>
        /// List转化为Json
        /// 浅层序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="IL"></param>
        /// <param name="flag">带标注为可以附带一些信息(默认为空)</param>
        /// <returns></returns>
        public static string ListToJson<T>(IList<T> IL, string flag = "")
        {
            System.Text.StringBuilder Json = new StringBuilder();
            Json.Append("{\"total\":\"" + flag + "\",\"rows\":");
            Json.Append(IL.ToJson());
            Json.Append("}");
            return Json.ToString();
        }

        /// <summary>
        /// 将object转换为json字符串
        /// </summary>
        /// <param name="source">数据源</param>
        /// <returns></returns>
        public static string ToJson(this Object source)
        {
            return ToJson(source, source.GetType());
        }
        /// <summary>
        /// 将object转换为json字符串
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="type">object数据类型</param>
        /// <returns></returns>
        public static string ToJson(Object source, Type type)
        {
            DataContractJsonSerializer serilializer = new DataContractJsonSerializer(type);
            using (MemoryStream stream = new MemoryStream())
            {
                serilializer.WriteObject(stream, source);
                string jsonString = Encoding.UTF8.GetString(stream.ToArray());
                stream.Flush();
                stream.Position = 0;

                string pattern = @"\\/Date\((\d+)\+\d+\)\\/";
                MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
                Regex reg = new Regex(pattern);
                jsonString = reg.Replace(jsonString, matchEvaluator);

                return jsonString;
            }
        }
        /// <summary>
        /// 将json字符转换为Object
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="str">json字符串</param>
        /// <returns></returns>
        public static T ParseJSON<T>(this string jsonString)
        {
            string pattern = @"\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
            Regex reg = new Regex(pattern);
            jsonString = reg.Replace(jsonString, matchEvaluator);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);

            return obj;
        }


        /// <summary>
        /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
        /// </summary>
        private static string ConvertJsonDateToDateString(Match m)
        {

            string result = string.Empty;

            DateTime dt = new DateTime(1970, 1, 1);

            dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));

            dt = dt.ToLocalTime();

            result = dt.ToString("yyyy-MM-dd HH:mm:ss");

            return result;

        }

        /// <summary>
        /// 将时间字符串转为Json时间
        /// </summary>
        private static string ConvertDateStringToJsonDate(Match m)
        {
            string result = string.Empty;
            DateTime dt = DateTime.Parse(m.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
            return result;
        }
    }
}